use actix_web::{post, web, Responder, HttpResponse};
use serde::{Deserialize, Serialize};
use serde_json::json;
use crate::{RB, service};
use crate::model::order::Order;
use crate::resp::resp::Resp;
use crate::util::logger;
use crate::model::order_add_dto::OrderAddDto;

#[allow(dead_code, unused_imports)]
#[post("/inner/upd_order_state_by_oid")]
pub async fn upd_order_state_by_oid(dto: web::Json<UpdOrderStateByOidDto>) -> impl Responder {
    let dto = dto.into_inner();
    let allows = vec![2,3,4];
    match allows.binary_search(&dto.clone().ostate.unwrap()) {
        Ok(_) => {
            //
        },
        Err(_) => {
            logger::errorMsg(format!("不允许的状态:{}", dto.clone().ostate.unwrap()));
            return HttpResponse::Ok().json(json!(Resp::fail("不允许的状态", 0, dto.clone())));
        }
    }
    let rb = RB.clone();
    let x0: Result<Order, rbatis::rbdc::Error> = rb.query_decode(&Order::sel(dto.clone().oid.unwrap()), vec![]).await;
    match x0 {
        Ok(order) => {
            if order.ostate==-1||order.ostate==1 {
                logger::warn(format!("订单{}已结束或已取消", order.oid.unwrap()));
                return HttpResponse::Ok().json(json!(Resp::fail("订单已结束或已取消", 0, dto.clone())));
            }
        },
        Err(_) => {
            logger::warn(format!("订单{}不存在", dto.clone().oid.unwrap()));
            return HttpResponse::Ok().json(json!(Resp::fail("订单不存在", 0, dto.clone())));
        }
    };
    rb.query(&Order::upd_state(dto.oid.unwrap(), dto.ostate.unwrap()), vec![]).await.unwrap();
    HttpResponse::Ok().json(json!(Resp::ok("修改成功", 0, ())))
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct UpdOrderStateByOidDto {
    oid: Option<String>,
    ostate: Option<i32>
}

#[allow(dead_code, unused_imports)]
#[post("/inner/order")]
pub async fn add_order(order_add_dto: web::Json<OrderAddDto>) -> impl Responder {
    return service::add_order(order_add_dto).await;
}